<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>随心画</title>
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <canvas id="canvas"></canvas>
    <script>
        var canvas = document.getElementById("canvas");
        canvas.width = document.documentElement.clientWidth;
        canvas.height = document.documentElement.clientHeight;
        let painting = false;
        var ctx = canvas.getContext("2d");
        ctx.fillStyle = "blue";
        ctx.strokeStyle = "blue";
        ctx.lineWidth = 10;
        ctx.lineCap = "round";

        function drawLine(lastX, lastY, x, y) {
            ctx.beginPath();
            ctx.moveTo(x, y);
            ctx.lineTo(lastX, lastY);
            ctx.stroke();
        }

        var isTouchDevice = 'ontouchstart' in document.documentElement;
        if (isTouchDevice) {
            canvas.ontouchstart = (e) => {
                let x = e.touches[0].clientX;
                let y = e.touches[0].clientY;
                last = [x, y];
            }
            canvas.ontouchmove = (e) => {
                let x = e.touches[0].clientX;
                let y = e.touches[0].clientY;
                drawLine(last[0], last[1], x, y);
                last = [x, y];
            }
        } else {
            canvas.onmousedown = (e) => {
                painting = true;
                lastX = e.clientX;
                lastY = e.clientY;
            }
            canvas.onmousemove = (e) => {
                if (painting === true) {
                    drawLine(lastX, lastY, e.clientX, e.clientY);
                    lastX = e.clientX;
                    lastY = e.clientY;
                }
            }
            canvas.onmouseup = () => {
                painting = false;
            }
        }
    </script>
</body>

</html>